package com.hkrt.demo.presentation.screen.login

import android.text.TextUtils
import com.alibaba.android.arouter.launcher.ARouter
import com.hkrt.demo.Const
import com.hkrt.demo.R
import com.hkrt.demo.data.response.LoginResponse
import com.hkrt.demo.presentation.base.BaseActivity
import com.hkrt.demo.presentation.utils.Base64
import com.hkrt.demo.presentation.utils.CommonUtils
import com.hkrt.demo.presentation.utils.MD5Util
import com.hkrt.demo.presentation.utils.extensions.onClick
import com.hkrt.demo.presentation.utils.extensions.showToast
import kotlinx.android.synthetic.main.activity_login.*
import javax.inject.Inject

/**
 * @author  陈金广
 * @date 2018/4/4.
 */
class LoginActivity : BaseActivity<LoginContract.View, LoginContract.Presenter>(), LoginContract.View {

    @Inject
    protected lateinit var loginPresenter: LoginPresenter

    override fun initLayoutId(): Int {
        return R.layout.activity_login
    }

    override fun initViewsAndEvents() {
        toolbar.inflateMenu(R.menu.main)
        btnLogin.onClick {
            checkLogin()
        }

        btnShowMain.onClick {
            ARouter.getInstance().build(Const.ROUTE_MAIN)
                    .withString("name","chenjinguang")
                    .withInt("age",30)
                    .navigation(this)
        }
    }

    private fun checkLogin() {
        val name = editPhone.text.toString().trim()
        val password = editPassword.text.toString().trim()
        if(TextUtils.isEmpty(name)){
            showToast("请输入用户名")
        }else if(TextUtils.isEmpty(password)){
            showToast("请输入密码")
        }else{
            showProgressDialog()
            val platform = "android"
            val time = CommonUtils.getTime()
            val appVersion = CommonUtils.getAppVersionName(this)
            val mac = MD5Util.MD5Encode(name + time, "")
            //密码第一次加密
            val md5pwd = Base64.encode(MD5Util.encryptMD5(password.toByteArray()))
            //密码第二次加密
            val pwd = MD5Util.generatePassword(password)
            loginPresenter.login(name, md5pwd + "," + pwd, time, "001", platform, appVersion, mac)
        }
    }

    override fun initPresenter(): LoginContract.Presenter = loginPresenter

    override fun injectDependencies() {
        activityComponent.inject(this)
    }

    override fun onLogined(result: LoginResponse) {
        hideProgressDialog()
        showToast(result.msg!!)
    }
}